<template>
  <div class="data-test-page">
    <div class="test-header">
      <el-card>
        <div class="header-content">
          <h2>仪表盘数据测试页面</h2>
          <p>用于测试API数据获取和显示效果</p>
          <div class="test-controls">
            <el-button type="primary" @click="testAllApis" :loading="loading">
              测试所有API
            </el-button>
            <el-button @click="clearResults">
              清空结果
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- API测试结果 -->
    <div class="test-results">
      <el-card v-for="(result, index) in testResults" :key="index" class="result-card">
        <template #header>
          <div class="result-header">
            <span class="api-name">{{ result.name }}</span>
            <el-tag :type="result.success ? 'success' : 'danger'">
              {{ result.success ? '成功' : '失败' }}
            </el-tag>
          </div>
        </template>
        
        <div class="result-content">
          <div class="api-info">
            <p><strong>接口地址:</strong> {{ result.url }}</p>
            <p><strong>响应时间:</strong> {{ result.responseTime }}ms</p>
            <p><strong>状态码:</strong> {{ result.status }}</p>
          </div>
          
          <div class="data-preview" v-if="result.success && result.data">
            <h4>返回数据预览:</h4>
            <pre class="json-preview">{{ JSON.stringify(result.data, null, 2) }}</pre>
          </div>
          
          <div class="error-info" v-if="!result.success">
            <h4>错误信息:</h4>
            <p class="error-message">{{ result.error }}</p>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 数据可视化测试 -->
    <div class="visualization-test" v-if="chartData.length > 0">
      <el-card>
        <template #header>
          <h3>数据可视化测试</h3>
        </template>
        
        <div class="charts-test-grid">
          <div class="chart-test-item" v-for="chart in chartData" :key="chart.name">
            <h4>{{ chart.name }}</h4>
            <div class="chart-container">
              <v-chart :option="chart.option" style="height: 250px;" />
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { ElMessage } from 'element-plus'
import {
  dashboardApi,
  studentDashboardApi,
  teacherDashboardApi,
  adminDashboardApi
} from '@/api/dashboard'
import { useUserStore } from '@/stores/user'

// 注册ECharts组件
use([
  CanvasRenderer,
  PieChart,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const userStore = useUserStore()
const loading = ref(false)
const testResults = ref<any[]>([])
const chartData = ref<any[]>([])

// API测试配置
const apiTests = computed(() => {
  const role = userStore.userInfo?.role
  const tests = [
    {
      name: '概览统计',
      url: '/api/dashboard/overview/',
      api: () => dashboardApi.getOverviewStats()
    },
    {
      name: '学生就业统计',
      url: '/api/dashboard/students/employment-statistics/',
      api: () => dashboardApi.getStudentEmploymentStats()
    },
    {
      name: '简历状态统计',
      url: '/api/dashboard/resume-management/statistics/',
      api: () => dashboardApi.getResumeStats()
    },
    {
      name: '面试状态统计',
      url: '/api/dashboard/interviews/statistics/',
      api: () => dashboardApi.getInterviewStats()
    },
    {
      name: '岗位状态统计',
      url: '/api/dashboard/jobs/statistics/',
      api: () => dashboardApi.getJobStats()
    },
    {
      name: '月度趋势',
      url: '/api/dashboard/monthly-trends/',
      api: () => dashboardApi.getMonthlyTrends({ months: 6 })
    }
  ]

  // 根据角色添加特定API
  if (role === 'admin') {
    tests.push(
      {
        name: '系统概览',
        url: '/api/dashboard/system-overview/',
        api: () => adminDashboardApi.getSystemOverview()
      },
      {
        name: '增长趋势',
        url: '/api/dashboard/growth-trends/',
        api: () => adminDashboardApi.getGrowthTrends()
      }
    )
  } else if (role === 'teacher') {
    tests.push(
      {
        name: '负责学生统计',
        url: '/api/dashboard/students/my-students-statistics/',
        api: () => teacherDashboardApi.getMyStudentsStats()
      },
      {
        name: '待审核简历',
        url: '/api/dashboard/resume-management/pending-reviews/',
        api: () => teacherDashboardApi.getPendingResumes()
      }
    )
  } else if (role === 'student') {
    tests.push(
      {
        name: '个人统计',
        url: '/api/dashboard/students/my-statistics/',
        api: () => studentDashboardApi.getPersonalStats()
      },
      {
        name: '简历进度',
        url: '/api/dashboard/resume-management/my-progress/',
        api: () => studentDashboardApi.getResumeProgress()
      }
    )
  }

  return tests
})

// 测试单个API
const testSingleApi = async (test: any) => {
  const startTime = Date.now()
  
  try {
    const response = await test.api()
    const endTime = Date.now()
    
    return {
      name: test.name,
      url: test.url,
      success: true,
      status: 200,
      responseTime: endTime - startTime,
      data: response.data
    }
  } catch (error: any) {
    const endTime = Date.now()
    
    return {
      name: test.name,
      url: test.url,
      success: false,
      status: error.response?.status || 0,
      responseTime: endTime - startTime,
      error: error.message || '未知错误'
    }
  }
}

// 测试所有API
const testAllApis = async () => {
  loading.value = true
  testResults.value = []
  chartData.value = []
  
  try {
    const tests = apiTests.value
    const results = []
    
    for (const test of tests) {
      const result = await testSingleApi(test)
      results.push(result)
      testResults.value.push(result)
      
      // 为成功的数据创建图表
      if (result.success && result.data) {
        createChartFromData(result)
      }
    }
    
    const successCount = results.filter(r => r.success).length
    const totalCount = results.length
    
    if (successCount === totalCount) {
      ElMessage.success(`所有 ${totalCount} 个API测试成功！`)
    } else {
      ElMessage.warning(`${successCount}/${totalCount} 个API测试成功`)
    }
    
  } catch (error) {
    ElMessage.error('API测试过程中发生错误')
  } finally {
    loading.value = false
  }
}

// 根据数据创建图表
const createChartFromData = (result: any) => {
  const { name, data } = result
  
  if (name === '学生就业统计') {
    chartData.value.push({
      name: '就业状态分布',
      option: {
        tooltip: { trigger: 'item' },
        series: [{
          type: 'pie',
          radius: '50%',
          data: [
            { value: data.employed, name: '已就业' },
            { value: data.unemployed, name: '未就业' },
            { value: data.further_study, name: '继续深造' },
            { value: data.self_employed, name: '自主创业' },
            { value: data.military, name: '参军入伍' }
          ]
        }]
      }
    })
  } else if (name === '月度趋势' && Array.isArray(data)) {
    chartData.value.push({
      name: '月度趋势图',
      option: {
        tooltip: { trigger: 'axis' },
        legend: { data: ['面试数量', '申请数量'] },
        xAxis: {
          type: 'category',
          data: data.map(item => item.month)
        },
        yAxis: { type: 'value' },
        series: [
          {
            name: '面试数量',
            type: 'line',
            data: data.map(item => item.interviews)
          },
          {
            name: '申请数量',
            type: 'line',
            data: data.map(item => item.applications)
          }
        ]
      }
    })
  } else if (name === '岗位状态统计' && data.applications) {
    chartData.value.push({
      name: '申请状态分布',
      option: {
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: ['待审核', '已通过', '已拒绝', '总申请']
        },
        yAxis: { type: 'value' },
        series: [{
          type: 'bar',
          data: [
            data.applications.pending,
            data.applications.approved,
            data.applications.rejected,
            data.applications.total
          ]
        }]
      }
    })
  }
}

// 清空结果
const clearResults = () => {
  testResults.value = []
  chartData.value = []
  ElMessage.info('测试结果已清空')
}
</script>

<style lang="scss" scoped>
.data-test-page {
  .test-header {
    margin-bottom: 24px;
    
    .header-content {
      h2 {
        margin: 0 0 8px 0;
        color: var(--text-color-primary);
      }
      
      p {
        margin: 0 0 16px 0;
        color: var(--text-color-secondary);
      }
      
      .test-controls {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .test-results {
    display: grid;
    gap: 16px;
    margin-bottom: 24px;
    
    .result-card {
      .result-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .api-name {
          font-weight: 600;
          color: var(--text-color-primary);
        }
      }
      
      .result-content {
        .api-info {
          margin-bottom: 16px;
          
          p {
            margin: 4px 0;
            font-size: 14px;
          }
        }
        
        .json-preview {
          background: var(--fill-color-light);
          padding: 12px;
          border-radius: 4px;
          font-size: 12px;
          max-height: 200px;
          overflow-y: auto;
        }
        
        .error-message {
          color: var(--color-danger);
          font-size: 14px;
        }
      }
    }
  }
  
  .visualization-test {
    .charts-test-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 24px;
      
      .chart-test-item {
        h4 {
          margin: 0 0 12px 0;
          color: var(--text-color-primary);
          text-align: center;
        }
        
        .chart-container {
          height: 250px;
        }
      }
    }
  }
}
</style>
